﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Support.DTO;
using System.Data.SqlClient;
using System.Data;

namespace DataAccess
{
    public class ProvinciaDAL : BaseSQLDAL
    {
        public List<ProvinciaDTO> GetProvincias()
        {
            List<ProvinciaDTO> provincias = new List<ProvinciaDTO>();

            try
            {

                CreateCommand("Provincia_Listado", true);

                ExecuteReader();
                while (Read())
                {
                    provincias.Add(FillDTO(GetDataReader()));
                }
                return provincias;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                DisposeCommand();
                DisposeDataReader();
                CloseConnection();
            }
        }

        private ProvinciaDTO FillDTO(SqlDataReader reader)
        {
            int id = reader.GetInt32(reader.GetOrdinal("IdProvincia"));
            string name = reader.GetString(reader.GetOrdinal("Nombre"));
            return new ProvinciaDTO()
            {
                Id = id,
                Name = name
            };
        }

        public ProvinciaDTO GetProvinciaById(int provinciaId)
        {
            try
            {
                ProvinciaDTO provincia = new ProvinciaDTO();
                CreateCommand("Provincia_ObtenerPorId", true);
                AddCmdParameter("@ProvinciaId", provinciaId, ParameterDirection.Input);

                ExecuteReader();
                while (Read())
                {
                    provincia = FillDTO(GetDataReader());
                }
                return provincia;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                DisposeCommand();
                DisposeDataReader();
                CloseConnection();
            }
        }
    }
}
